package com.cti.commons.mqtt.domain;

import java.util.Optional;

import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.springframework.util.StringUtils;

import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.util.StrUtil;
import lombok.Data;

/**
 * 订阅topic
 */
@Data
public class SubscriptTopic {

    /**
     * 原主题
     */
    private String topic;

    /**
     * 共享主题
     */
    private String shareTopic;

    /**
     * 订阅模式
     */
    private ShareMode shareMode;

    /**
     * 消息等级
     */
    private int qos;

    /**
     * 消费类
     */
    private IMqttMessageListener messageListener;

    public SubscriptTopic(PahoTopic topic, IMqttMessageListener listener) {
        this.topic = topic.getTopic();
        this.shareMode = topic.getShareMode();
        this.decideShareTopic(topic);
        this.qos = Optional.ofNullable(topic.getQos()).orElse(1);
        this.messageListener = listener;
    }

    private void decideShareTopic(PahoTopic pahoTopic) {
        if (StringUtils.isEmpty(pahoTopic.getShareMode())) {
            this.shareTopic = "$queue/" + pahoTopic.getTopic();
            return;
        }
        switch (pahoTopic.getShareMode()) {
            case SHARE: {
                if (StrUtil.isEmpty(pahoTopic.getGroup())) {
                    throw new ValidateException("MQTT使用共享订阅需要设置分组名称 @Topic(group=\"xxx\")");
                }
                StringBuffer sb = new StringBuffer("$share");
                sb.append("/" + pahoTopic.getGroup());
                if (StrUtil.isNotBlank(pahoTopic.getTopic())) {
                    sb.append("/" + pahoTopic.getTopic());
                }
                this.shareTopic = sb.toString();
                break;
            }
            case QUEUE:
            default: {
                this.shareTopic = "$queue/" + pahoTopic.getTopic();
                break;
            }
        }
    }

}
